import React, { useState, useCallback } from "react";
import { NextPage } from "next";
import InfinityScroll from "react-infinite-scroller";
import cls from "classnames";

import style from "./index.module.scss";
import { ArticleList } from "@/components/ArticleList";
import { ArticleApi } from "@/api/article";
import { Recommend } from "@/components/Recommend";
import { Categories } from "@/components/Categories";
import { Tags } from "@/components/Tags";
import { useAffix } from "@/components/Header/useAffix";
import { Footer } from "@/components/Footer";

interface IHomeProps {
  articles: IArticle[];
  total: number;
}
const pageSize = 8;
const Home: NextPage<IHomeProps> = props => {
  const {
    articles: defaultArticle = [],
    tags,
    categorys,
    total = 0,
    setting
  } = props as any;
  const [articles, setArticles] = useState(defaultArticle);
  // const [affix, affixVisible] = useAffix(64, true);
  // 当前页数，从第二页开始获取，因为在服务端默认加载了第一页
  const [page, setPage] = useState(1);
  const getArticles = useCallback(page => {
    ArticleApi.getArticles({ page, pageSize, status: "publish" }).then(res => {
      setArticles(articles => [...articles, ...res[0]]);
      setPage(page);
    });
  }, []);

  return (
    <div className={style.wrapper}>
      <div className="container">
        <div className={style.content}>
          <div className={style.list}>
            <InfinityScroll
              pageStart={1}
              loadMore={getArticles}
              hasMore={page * pageSize < total}
              loader={
                <div className={style.loading} key={0}>
                  正在获取文章...
                </div>
              }
            >
              <ArticleList articles={articles} />
            </InfinityScroll>
          </div>
          <aside className={cls(style.aside)}>
            <div /**className={cls(affix ? style.affix : null)}*/>
              <Recommend />
              <Categories categorys={categorys} />
              <Tags tags={tags} />
              <Footer setting={setting} />
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
};

// 服务端预取数据
Home.getInitialProps = async () => {
  const [articles] = await Promise.all([
    ArticleApi.getArticles({ page: 1, pageSize, status: "publish" })
  ]);
  return { articles: articles[0], total: articles[1], needLayoutFooter: false };
};
export default Home;
